package model

import (
	"github.com/BurntSushi/toml"
	"log"
	"os"
	"path/filepath"
)

func Encoder(configPath string) {
	err := os.MkdirAll(filepath.Dir(configPath), os.ModePerm)
	if err != nil {
		log.Fatal("Create Dir:", err)
		return
	}
	file, err := os.Create(configPath)
	if err != nil {
		log.Fatal("Create File:", err)
		return
	}
	defer file.Close()
	encode := toml.NewEncoder(file)
	config := NewConfig(
		SetDatasource("mysql", Datasource{
			DbType:   "mysql",
			HostURL:  "192.168.20.9:3306",
			Database: "EmpShop",
			Username: "root",
			Password: "root",
		}), SetDatasource("redis", Datasource{
			DbType:   "redis",
			HostURL:  "192.168.20.9:6380",
			Database: "0",
			Password: "root",
		}), SetDatasource("mongo", Datasource{
			DbType:   "mongo",
			HostURL:  "192.168.20.9:27017",
			Database: "EmpShop",
			Username: "root",
			Password: "root",
		}),
		SetEtcd(Etcd{
			URL: "192.168.20.9:27017",
			Key: "MainServer",
			Children: []Etcd{
				{
					URL:      "192.168.20.9:27017",
					Key:      "Order",
					Children: nil,
				}, {
					URL:      "192.168.20.9:27017",
					Key:      "Pay",
					Children: nil,
				},
			},
		}),
		SetNsq(Nsq{HostURL: "192.168.20.9:4150"}),
		SetInfluxdb(InfluxConfig{
			HostURL: "http://192.168.20.9:8086",
			Bucket:  "EmpShop",
			Org:     "eliza",
			Token:   "E_vJE297onN_hRoouMSugZQOX8YH7BcsrwZbU2tgrkLYSRN8MCwwk-wk7A2g6D7kaIHWU_AGW37hL83Fq_F13A==",
		}),
	)

	if err = encode.Encode(config); err != nil {
		panic(err)
	}

}
func DecodeFile(configPath string) *Config {
	if _, err := os.Stat(configPath); err != nil {
		configPath = "../config/config.toml"
	}
	var config Config
	_, err := toml.DecodeFile(configPath, &config)
	if err != nil {
		log.Fatal(err, "DecodeFile")
		os.Exit(1)
	}

	return &config
}
